<template>
  <div class="page-container">
    <h2>活动设置</h2>
    <div class="setting-form">
      <a-form :model="activityForm" layout="vertical">
        <a-form-item label="活动标题">
          <a-input
            v-model:value="activityForm.title"
            placeholder="请输入活动标题"
          />
        </a-form-item>
        <a-form-item label="活动副标题">
          <a-input
            v-model:value="activityForm.subtitle"
            placeholder="请输入活动副标题"
          />
        </a-form-item>
        <a-form-item label="活动描述">
          <a-input.TextArea
            v-model:value="activityForm.description"
            placeholder="请输入活动描述"
            rows="4"
          />
        </a-form-item>
        <a-button type="primary" @click="saveActivitySettings">
          保存设置
        </a-button>
      </a-form>
    </div>
  </div>
</template>

<script>
import { reactive, onMounted } from "vue";
import { baseApi } from "../../api";

export default {
  name: "Draw",
  setup() {
    // 活动设置表单
    const activityForm = reactive({
      title: "大屏抽奖活动",
      subtitle: "幸运抽奖，惊喜不断",
      description: "参与抽奖，赢取精美奖品！",
    });

    // 保存活动设置
    const saveActivitySettings = async () => {
      try {
        // 尝试保存到后端
        await baseApi.saveSettings(activityForm);
        // 同时保存到本地存储作为备份
        localStorage.setItem("activitySettings", JSON.stringify(activityForm));
        alert("活动设置保存成功！");
      } catch (error) {
        // 如果后端调用失败，仍然保存到本地存储
        localStorage.setItem("activitySettings", JSON.stringify(activityForm));
        console.warn("后端保存失败，已保存到本地存储:", error);
        alert("活动设置已保存到本地存储！");
      }
    };

    // 初始化加载数据
    const loadData = async () => {
      try {
        // 优先从后端加载活动设置
        const result = await baseApi.getSettings();
        if (result.data) {
          Object.assign(activityForm, result.data);
          // 同时保存到本地存储作为备份
          localStorage.setItem(
            "activitySettings",
            JSON.stringify(activityForm)
          );
        }
      } catch (error) {
        // 如果后端调用失败，从本地存储加载
        console.warn("后端加载失败，从本地存储加载:", error);
        const savedSettings = localStorage.getItem("activitySettings");
        if (savedSettings) {
          Object.assign(activityForm, JSON.parse(savedSettings));
        }
      }
    };

    onMounted(() => {
      loadData();
    });

    return {
      activityForm,
      saveActivitySettings,
    };
  },
};
</script>

<style scoped>
.page-container {
  min-height: 600px;
}

.setting-form {
  max-width: 600px;
  margin-top: 20px;
}
</style>
